package me.flyray.common.util;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ValidateSign {
	private final static Logger logger = LoggerFactory.getLogger(ValidateSign.class);
    /**
     * @author myq
     * @param sign 请求中的签名，key 请求中生产签名用的盐值， parammap 生产签名要用的参数串
     * @return
     */
    public static boolean checkSign(String sign,String key,Map<String, Object> parammap) {
    	String str = createLinkString(parammap);
    	logger.info("参与签名字符串：--" + str);
    	String result = str + "&key=" + key;
    	logger.info("拼接密钥后的签名字符串：--" + result);
    	String mysign = HmacSHA256Utils.sha256_HMAC(result, key).toUpperCase();
    	if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }
    
    private static String createLinkString(Map<String, Object> params) {

		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);

		String prestr = "";

		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			if (!"sign".equals(key)) {
				Object obj = params.get(key);
				if (obj == null || "".equals(obj)) {
					continue;
				}
				String value = String.valueOf(obj);
				prestr = prestr + key + "=" + value + "&";
			}
		}

		return prestr.substring(0, prestr.length() - 1);

	}
    
}
